package the.lb.workbench.auth.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import the.broccoli.uc.entity.User;
import the.lb.workbench.auth.po.AuthUser;
import the.lb.workbench.auth.shiro.factory.DataFactory;
import the.lb.workbench.auth.shiro.factory.IData;

public class ShiroDbRealm extends AuthorizingRealm {

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        IData ds = DataFactory.me();
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = ds.user(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException();
        }
        AuthUser authUser = ds.authUser(user);
        return info(authUser, user.getPassword(), super.getName());
    }

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 设置认证加密方式
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        md5CredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(md5CredentialsMatcher);
    }

    private SimpleAuthenticationInfo info(AuthUser authUser, String credentials, String realmName) {
        ByteSource credentialsSalt = new Md5Hash("wisteria");
        return new SimpleAuthenticationInfo(authUser, credentials, credentialsSalt, realmName);
    }

}
